// utils/config.js
const config = {
  // 后端API基础地址
  apiBaseUrl: 'http://8.137.20.120:5000/api',
  
  // 默认设备ID
  defaultDeviceId: 1,
  
  // 数据轮询间隔（毫秒）
  pollingInterval: 5000,
  
  // 最大重试次数
  maxRetries: 3,
  
  // 重试延迟（毫秒）
  retryDelay: 1000,
  
  // 超时设置（毫秒）
  timeout: 10000
};

// 通用请求函数
const request = (method, endpoint, data = {}, header = {}) => {
  return new Promise((resolve, reject) => {
    const token = wx.getStorageSync('token') || '';
    const headers = {
      'Content-Type': 'application/json',
      ...header
    };
    
    if (token) {
      headers.Authorization = `Bearer ${token}`;
    }
    
    wx.request({
      url: `${config.apiBaseUrl}${endpoint}`,
      method: method,
      header: headers,
      data: data,
      timeout: config.timeout,
      success: (res) => {
        if (res.statusCode === 200 && res.data.status === 'success') {
          resolve(res.data);
        } else {
          reject(res.data.message || '请求失败');
        }
      },
      fail: (err) => {
        reject('网络错误');
      }
    });
  });
};

// 带重试机制的请求
const requestWithRetry = async (method, endpoint, data = {}, header = {}, retries = config.maxRetries) => {
  try {
    return await request(method, endpoint, data, header);
  } catch (error) {
    if (retries > 0) {
      await new Promise(resolve => setTimeout(resolve, config.retryDelay));
      return requestWithRetry(method, endpoint, data, header, retries - 1);
    }
    throw error;
  }
};

// API方法
const api = {
  // 用户相关
  register: (username, password) => requestWithRetry('POST', '/user/register', { username, password }),
  login: (username, password) => requestWithRetry('POST', '/user/login', { username, password }),
  getUserInfo: () => requestWithRetry('GET', '/user/info'),
  
  // 设备相关
  uploadDeviceData: (data) => requestWithRetry('POST', '/data/upload', data),
  queryDeviceData: (deviceId, startTime, endTime) => requestWithRetry('POST', '/data/query', { 
    device_id: deviceId, 
    start_time: startTime,
    end_time: endTime
  }),
  getDeviceStatus: (deviceId) => requestWithRetry('GET', '/device/status', { device_id: deviceId }),
  registerDevice: (deviceData) => requestWithRetry('POST', '/device/register', deviceData),
  sendHeartbeat: (deviceData) => requestWithRetry('POST', '/device/heartbeat', deviceData),
  checkFirmware: (deviceId, currentFw) => requestWithRetry('POST', '/device/firmware/check', {
    device_id: deviceId,
    current_firmware: currentFw
  }),
  sendAlert: (alertData) => requestWithRetry('POST', '/device/alert', alertData)
};

module.exports = {
  config,
  request,
  requestWithRetry,
  api
};